var net = require('net');
var netpkg = require('./netpkg');
var protocol = require('./protocol');
var protocoljson = require('./protojson');
/**
 * 服务端sever
 */
function process_one_cmd(sock, cmd) {
    console.log(cmd);

    //解码二进制
    // var data = protocol.decode(cmd);
    // console.log('服务端解码二进制数据局', data);

    //解码json
    var data = protocoljson.decode(cmd);
    console.log('服务端解码json数据局', data);
}

var server = net.createServer((client_sock)=>{
    console.log('======createServer=======',client_sock.remoteAddress,client_sock.remotePort);

    //记录上一次未完成的数据，即半个包
    client_sock.last_pkg = null;

    client_sock.on('close',function(e){
        console.log('======client_sock err===========',e);
    })
 
    client_sock.on("data", function(data) {
        console.log('=======client_sock=data========',data);

        var cmd_set = netpkg.unpack_cmd_from_data(client_sock,data);
        for(var key in cmd_set) {
            process_one_cmd(client_sock, cmd_set[key]);
        }
    });

    client_sock.on('error',function(err){
        console.log('err',err);
    })
})

server.on('connection',function(){
    console.log('======server=connection========');
});

server.on('listening',function(){
    console.log("start listening...");
});

server.on('close',function(){
    console.log('=====server=close===========');
});

server.on('error',function(err){
    console.log('=====server=error===========',err);
});

server.listen({
	port: 6080,
	host: "127.0.0.1",
	exclusive: true,
});
